package com.linden.std.Utils;

import com.linden.std.constant.CommonConstant;
import com.linden.std.domain.vo.UserVO;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.List;

/**
 * Session工具类
 * 提供便捷的Session操作方法
 */
public class SessionUtil {

    /**
     * 获取当前请求的HttpSession
     *
     * @return HttpSession对象，如果获取失败返回null
     */
    public static HttpSession getCurrentSession() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                return request.getSession(false);
            }
        } catch (Exception e) {
            // 忽略异常，返回null
        }
        return null;
    }

    /**
     * 从Session获取用户信息
     *
     * @return 用户信息，如果不存在返回null
     */
    public static UserVO getUserFromSession() {
        HttpSession session = getCurrentSession();
        if (session != null) {
            try {
                return (UserVO) session.getAttribute(CommonConstant.SESSION_USER_KEY);
            } catch (Exception e) {
                // 忽略异常，返回null
            }
        }
        return null;
    }

    /**
     * 从Session获取权限信息
     *
     * @return 权限列表，如果不存在返回空列表
     */
    @SuppressWarnings("unchecked")
    public static List<String> getPermissionsFromSession() {
        HttpSession session = getCurrentSession();
        if (session != null) {
            try {
                List<String> permissions = (List<String>) session.getAttribute(CommonConstant.SESSION_PERMISSION_KEY);
                return permissions != null ? permissions : Collections.emptyList();
            } catch (Exception e) {
                // 忽略异常，返回空列表
            }
        }
        return Collections.emptyList();
    }

    /**
     * 设置用户信息到Session
     *
     * @param userVO 用户信息
     */
    public static void setUserToSession(UserVO userVO) {
        HttpSession session = getCurrentSession();
        if (session != null && userVO != null) {
            try {
                session.setAttribute(CommonConstant.SESSION_USER_KEY, userVO);
            } catch (Exception e) {
                // 忽略异常
            }
        }
    }

    /**
     * 设置权限信息到Session
     *
     * @param permissions 权限列表
     */
    public static void setPermissionsToSession(List<String> permissions) {
        HttpSession session = getCurrentSession();
        if (session != null) {
            try {
                List<String> safePermissions = permissions != null ? permissions : Collections.emptyList();
                session.setAttribute(CommonConstant.SESSION_PERMISSION_KEY, safePermissions);
            } catch (Exception e) {
                // 忽略异常
            }
        }
    }

    /**
     * 清理Session中的用户信息
     */
    public static void clearSessionUserInfo() {
        HttpSession session = getCurrentSession();
        if (session != null) {
            try {
                session.removeAttribute(CommonConstant.SESSION_USER_KEY);
                session.removeAttribute(CommonConstant.SESSION_PERMISSION_KEY);
            } catch (Exception e) {
                // 忽略异常
            }
        }
    }

    /**
     * 获取当前用户ID
     *
     * @return 用户ID，如果不存在返回null
     */
    public static Long getCurrentUserId() {
        UserVO user = getUserFromSession();
        return user != null ? user.getUserId() : null;
    }

    /**
     * 获取当前用户名
     *
     * @return 用户名，如果不存在返回null
     */
    public static String getCurrentUsername() {
        UserVO user = getUserFromSession();
        return user != null ? user.getAccount() : null;
    }

    /**
     * 检查当前用户是否拥有指定权限
     *
     * @param permission 权限代码
     * @return 是否拥有权限
     */
    public static boolean hasPermission(String permission) {
        if (permission == null || permission.trim().isEmpty()) {
            return false;
        }
        List<String> permissions = getPermissionsFromSession();
        return permissions.contains(permission);
    }

    /**
     * 检查当前用户是否拥有指定权限中的任意一个
     *
     * @param permissions 权限代码列表
     * @return 是否拥有任意一个权限
     */
    public static boolean hasAnyPermission(String... permissions) {
        if (permissions == null || permissions.length == 0) {
            return false;
        }
        List<String> userPermissions = getPermissionsFromSession();
        for (String permission : permissions) {
            if (userPermissions.contains(permission)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查当前用户是否拥有所有指定权限
     *
     * @param permissions 权限代码列表
     * @return 是否拥有所有权限
     */
    public static boolean hasAllPermissions(String... permissions) {
        if (permissions == null || permissions.length == 0) {
            return true;
        }
        List<String> userPermissions = getPermissionsFromSession();
        for (String permission : permissions) {
            if (!userPermissions.contains(permission)) {
                return false;
            }
        }
        return true;
    }
}